<?php

namespace app\merchant\controller\content\article;

use app\merchant\controller\Base;
use app\merchant\model\article\Category as CategoryModel;

/**
 * 文章分类
 * Class Category
 * @package app\merchant\controller\content
 */
class Category extends Base
{
    /**
     * 文章分类列表
     * @return mixed
     */
    public function index()
    {
        $model = new CategoryModel;
        $list = $model->getAll();
        return $this->renderSuccess($list,"查询成功");
    }


    /**
     * 添加文章分类
     * @return array|mixed
     */
    public function add()
    {
        $model = new CategoryModel;
        // 新增记录
        if ($model->add($this->postData())) {
            return $this->renderSuccess([],'添加成功');
        }
        return $this->renderError([],$model->getError() ?: '添加失败');
    }

    /**
     * 编辑文章分类
     * @param $category_id
     * @return array|mixed
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $param = $this->postData();
        if (!isset($param['category_id']) || isInt($param['category_id'])) {
            return $this->renderError([],"参数错误");
        }
        // 文章详情
        $model = CategoryModel::detail($param['category_id']);
        if (empty($model)) {
            return $this->renderError([],"分类不存在，请刷新重试");
        }

        // 更新记录
        if ($model->edit($this->postData())) {
            return $this->renderSuccess([],'更新成功');
        }
        return $this->renderError([],$model->getError() ?: '更新失败');
    }

    /**
     * 删除文章分类
     * @param $category_id
     * @return array
     * @throws \think\exception\DbException
     */
    public function delete($category_id)
    {
        $param = $this->postData();
        if (!isset($param['category_id']) || isInt($param['category_id'])) {
            return $this->renderError([],"参数错误");
        }
        // 文章详情
        $model = CategoryModel::detail($param['category_id']);
        if (empty($model)) {
            return $this->renderError([],"分类不存在，请刷新重试");
        }

        if (!$model->remove($param['category_id'])) {
            return $this->renderError([],$model->getError() ?: '删除失败');
        }
        return $this->renderSuccess([],'删除成功');
    }

}
